package com.tulei.admin.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Random;

@RestController
public class StockController {

    @GetMapping(value = "/stock-price", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamStockPrice() {
        SseEmitter emitter = new SseEmitter();

        // 模拟生成实时数据并推送给客户端
        String message = "Hello, SSE! 而法国热哦桂萼会如期归还入股和夫人吩咐热狗肺热五个人国王维托哈哈而愤然费率高了个人发v但是";

        new Thread(() -> {
            try {
                for (int i = 0; i < message.length(); i++) {
                    char c = message.charAt(i);
                    // 发送单个字符给客户端
                    emitter.send(SseEmitter.event().data(String.valueOf(c)));
                    // 休眠1秒钟
                    Thread.sleep(100);
                }
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();
        return emitter;
    }
}

